//################################
// 版权所有：中国农业银行软件开发中心
// 系统名称：移动办公应用-手机版
// 文件名称：index.js
// 创建时间：2016年09月22日
// 创建人员：Panda
// 功能说明：附件下载组件
//################################

'use strict';

import React, {Component} from 'react';
import {
    View,
    Text,
    StyleSheet,
    TouchableOpacity,
    Dimensions,
} from 'react-native';

import {
    FontSizes,
    Colors,
    UIConstants,
    PubSubTopics,
    CommonFunc,
} from '../../common';

import PubSub from 'pubsub-js';
import RNFS from 'react-native-fs';
import FileOpener from 'react-native-file-opener';
import LinearGradient from 'react-native-linear-gradient';
import ProgressBar from '../pandaProgress/Bar';

import Modal from '../modal';
import Button from '../button';

const WINDOW_WIDTH = Dimensions.get('window').width;
const WINDOW_HEIGHT = Dimensions.get('window').height;

class AttachmentDownloadModal extends Component {
    constructor(props) {
        super(props);
        // this.downloadRootFolder = RNFS.DocumentDirectoryPath + '/' + UIConstants.download.dir;
        this.downloadRootFolder = RNFS.ExternalDirectoryPath + '/' + UIConstants.download.dir;

        this.state = {
            isOpen: false,
            isDownloading: true,
            downloadTip: UIConstants.download.downloadStart,
            downloadPercentage:0,
        };

        this.init();
    }

    componentDidMount() {
        this.onAttachmentDownloadModalOpenEvent = PubSub.subscribe(PubSubTopics.ATTACHMENT_DOWNLOAD_MODAL_OPEN, (event, attachment) => {this.onAttachmentDownloadModalOpenHandler(attachment)});
    }

    componentWillUnmount() {
        PubSub.unsubscribe(this.onAttachmentDownloadModalOpenEvent);
    }
    
    onAttachmentDownloadModalOpenHandler(attachment) {
        this.init();

        this.attachment = attachment;

        this.setState({
            isOpen: true,
            isDownloading: true,
            downloadTip: UIConstants.download.downloadStart,
            downloadPercentage:0,
        });

        this.prepareToDownload();
    }

    prepareToDownload() {
        // 检查文件是否已经下载了，如果没下载则下载，如果已经下载了则打开
        // 文件下载的路径 RNFS/ABCFileDownloadFolder/BelongingType[zhsoi|zxsoi|email|coorperation]/ID[docId|emailId]/[{zhsoi|zxsoi?soi|yiju}/]fileName

        this.downloadLocalPath = this.getFileLocalPath();

        this.checkIsLocalFolderExists();
    }

    getFileLocalPath() {
        // return this.downloadRootFolder;

        //计算文件下载之后的路径
        let array = [];
        array.push(this.downloadRootFolder);
        array.push(this.attachment.belongingType);
        array.push(this.attachment.belongingId);
        
        if (this.attachment.isYijuAtt === true) {
            array.push('yiju');
        }
        else if (this.attachment.isYijuAtt === false) {
            array.push('soi');
        }

        if (this.attachment.fileId && this.attachment.parentFileName && this.attachment.parentFileName !== '') {
            array.push(this.attachment.parentFileName);
        }

        return array.join('/');
    }

    getFileName() {
        //计算文件下载之后的文件名
        let array = [];
        array.push(this.attachment.belongingType);
        array.push(this.attachment.belongingId);
        
        if (this.attachment.isYijuAtt === true) {
            array.push('yiju');
        }
        else if (this.attachment.isYijuAtt === false) {
            array.push('soi');
        }

        if (this.attachment.fileId && this.attachment.parentFileName && this.attachment.parentFileName !== '') {
            array.push(this.attachment.parentFileName);
        }

        array.push(this.attachment.fileName);

        return array.join('_');
    }

    checkIsLocalFolderExists() {
        RNFS.exists(this.downloadLocalPath)
        .then((isExist) => {
            if (isExist) {
                console.log('download folder exists');
                //下载目录存在，判断文件是否存在
                this.checkIsFileExists();
            }
            else {
                console.log('download folder not exists');
                //下载目录不存在，创建下载目录
                this.createDownloadLocalFolder();
            }
        },
        (error) => {
            console.log('check local folder exists rejected:' + error);
            //for test
            this.deleteDir();
        })
        .catch((error) => {
            console.log('checkIsLocalFolderExists error:' + error);
            //for test
            this.deleteDir();
        });
    }

    checkIsFileExists() {
        this.downloadDest = this.downloadLocalPath + '/' + this.attachment.fileName;
        // this.downloadDest = this.downloadLocalPath + '/' + this.getFileName();

        RNFS.exists(this.downloadDest)
        .then((isExist) => {
            if (isExist) {
                console.log('file exists');

                this.setState({
                    downloadTip: UIConstants.download.downloadComplete,
                    isDownloading: false,
                    downloadPercentage:100,
                });

                //文件已经下载过了，直接让用户选择要使用什么工具打开文件
                setTimeout(() => {
                    this.downloadFileComplete();
                }, 500);
            }
            else {
                console.log('file not exists');
                //文件未下载，准备开始下载
                this.downloadFileBegin();
            }
        },
        (error) => {
            console.log('check file exists rejected:' + error);
            //for test
            this.deleteDir();
        })
        .catch((error) => {
            console.log('checkIsFileExists error:' + error);
            //for test
            this.deleteDir();
        });
    }

    createDownloadLocalFolder() {
        RNFS.mkdir(this.downloadLocalPath)
        .then(() => {
            console.log('download folder created success');
            //目录创建完毕，开始下载
            this.downloadFileBegin();
        },
        (error) => {
            console.log('download folder created rejected:' + error);
            //for test
            this.deleteDir();
        })
        .catch((error) => {
            console.log('createDownloadLocalFolder error:' + error);
            //for test
            this.deleteDir();
        });
    }

    downloadFileComplete() {
        this.setState({
            downloadPercentage:100,
        })
        //下载完成
        this.openFile();
    }

    downloadFileBegin() {
        //开始下载
        let progress = (data) => {
            let percentage = ((100 * data.bytesWritten) / data.contentLength) | 0;

            console.log('download ' + percentage);
            
            this.setState({
                downloadTip: UIConstants.download.downloading.replace(UIConstants.download.percent, percentage),
                downloadPercentage:percentage,
            });
        };

        let begin = (res) => {
            this.jobId = res.jobId;

            console.log('download is about to begin');

            this.setState({
                downloadTip: UIConstants.download.downloading.replace(UIConstants.download.percent, 0),
                downloadPercentage:0
            })
        };

        let progressDivider = 11;

        if (this.downloadDest === '') {
            this.downloadDest = this.downloadLocalPath + '/' + this.attachment.fileName;
            // this.downloadDest = this.downloadLocalPath + '/' + this.getFileName();
        }

        // this.downloadDest = RNFS.ExternalDirectoryPath + '/' + this.attachment.fileName;

        let downloadUrl = this.getDownloadUrl();
        console.log('download url:' + downloadUrl);
        console.log('download to:' + this.downloadDest);

        let downloadParam = {
            fromUrl: downloadUrl,
            toFile: this.downloadDest,
            begin: begin,
            progress: progress,
            background: false,
            progressDivider: progressDivider,
        };

        RNFS.downloadFile(downloadParam)
        .promise.then((res) => {
            console.log('download is complete');
            //下载完成
            this.jobId = -1;

            this.setState({
                downloadTip: UIConstants.download.downloadComplete,
                isDownloading: false,
                downloadPercentage:100
            });
        },
        (error) => {
            console.log('download is rejected:' + error);
            //for test
            this.deleteDir();
        })
        .catch((error) => {
            console.log('download error:' + error);
            this.setState({
                downloadTip: error,
                isDownloading: false,
            });
            //for test
            this.deleteDir();
        });
    }

    getDownloadUrl() {
        if (this.attachment.fileId) {
            //压缩包中的文件下载地址计算
            return this.getDownloadUrlTemplate().replace('{sourceFile}', this.attachment.fileId).replace('{moduleId}', this.attachment.moduleId);
        }
        else {
            //非压缩包中的文件下载地址计算
            console.log('sourceFile:' + this.attachment.url);
            return this.getDownloadUrlTemplate().replace('{sourceFile}', encodeURIComponent(encodeURIComponent(decodeURIComponent(this.attachment.url)))).replace('{moduleId}', this.attachment.moduleId);
        }
    }

    getDownloadUrlTemplate() {
        return 'http://' + CommonFunc.getServerConfig('server') + '/' + CommonFunc.getServerConfig('context') + '/getfile/?sourceFile={sourceFile}&moduleId={moduleId}';
    }

    cancelDownload() {
        if (this.jobId !== -1) {
            RNFS.stopDownload(this.jobId);
            this.closeModal();
        }
        else {
            this.closeModal();
        }
        
    }

    deleteDir() {
        RNFS.unlink(this.downloadRootFolder)
        // RNFS.unlink(this.downloadDest)
        .then(() => {
            console.log('deleteDir complete');
        },
        (error) => {
            console.log('deleteDir is rejected:' + error);
        })
        .catch((error) => {
            console.log('deleteDir error:' + error);
        });
    }

    openFile() {
        console.log('open file:' + this.downloadDest);

        let mimeType = this.getMIMEType();

        FileOpener.open(this.downloadDest, mimeType)
        .then(() => {
            console.log('FileOpener resolve success');

            //成功打开附件之后关闭当前的下载页面
            // this.closeModal();
        },
        (error) => {
            console.log('FileOpener reject:' + error);

            PubSub.publish(PubSubTopics.TOAST_MODAL_OPEN, UIConstants.download.openError);
            //for test
            // this.deleteDir();
        })
        .catch((error) => {
            console.log('FileOpener failed:' + error);
            //for test
            // this.deleteDir();
        });
    }

    getMIMEType() {
        let suffix = this.downloadDest.toLowerCase().substring(this.downloadDest.lastIndexOf('.'), this.downloadDest.length);

        switch (suffix) {
            case '.docx':
            case '.doc':
                return 'application/msword';
            case '.wps':
                return 'application/vnd.ms-works';
            case '.pdf':
                return 'application/pdf';
            case '.xlss':
            case '.xls':
            case '.et':
                return 'application/vnd.ms-excel';
            case '.pptx':
            case '.ppt':
            case '.dps':
                return 'application/vnd.ms-powerpoint';
            case '.jpg':
            case '.jpeg':
                return 'image/jpeg';
            case '.gif':
                return 'image/gif';
            case '.txt':
                return 'text/plain';
            case '.png':
                return 'image/png';
        }
    }

    init() {
        this.jobId = -1;
        this.attachment = null;
        this.downloadLocalPath = '';
        this.downloadDest = '';
    }

    openModal() {
        this.setState({
            isOpen: true,
        });
    }

    closeModal() {
        this.deleteDir();
        this.setState({
            isOpen: false,
        });
    }
    
    render() {
        return (
            <Modal isOpen={this.state.isOpen} backdropPressToClose={false} isBackdropColorTransparent={true}>
                <LinearGradient colors={['#FFFFFF00', 'white', '#FFFFFF00']} style={styles.container}>
                    <View style={styles.downloadtipview}>
                        <Text style={styles.downloadtip}>{this.state.downloadTip}</Text>
                    </View>
                    <ProgressBar progress={this.state.downloadPercentage/100} width={WINDOW_WIDTH*0.8} height={13} color={Colors.green} borderRadius={8}/>
                    {
                        this.state.isDownloading ?
                        <View style={styles.buttonview}>
                            <Button text={UIConstants.download.cancelDownload} onPress={() => {this.cancelDownload()}} style={styles.button} textStyle={styles.buttontext} />
                        </View>
                        :
                        <View style={styles.buttonview}>
                            <Button text={UIConstants.download.openDownload} onPress={() => {this.openFile()}} style={styles.button} textStyle={styles.buttontext} />
                            <Button text={UIConstants.download.close} onPress={() => {this.closeModal()}} style={styles.closeButton} textStyle={styles.closebuttontext} />
                        </View>
                    }
                </LinearGradient>
            </Modal>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        width: WINDOW_WIDTH,
        height: WINDOW_HEIGHT,
        alignItems: 'center',
        flexDirection: 'column',
        justifyContent: 'center',
        backgroundColor: Colors.downloadBackground,
    },
    downloadtipview: {
        flexDirection: 'column',
        height: WINDOW_HEIGHT / 4,
        justifyContent: 'flex-end',
        marginBottom: 50,
    },
    downloadtip: {
        fontSize: FontSizes.downloadTip,
        fontWeight: 'bold',
        color: Colors.downloadTip,
    },
    buttonview: {
        marginTop: 50,
        flexDirection: 'column',
        height: WINDOW_HEIGHT / 4,
        justifyContent: 'flex-start',
    },
    button: {
        width: WINDOW_WIDTH / 3,
        height: WINDOW_WIDTH / 9,
        alignItems: 'center',
        justifyContent: 'center',
    },
    buttontext: {
        fontSize: FontSizes.downloadButtonText,
    },
    closeButton: {
        width: WINDOW_WIDTH / 3,
        height: WINDOW_WIDTH / 9,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: Colors.downloadCloseButton,
        marginTop: 20,
    },
    closebuttontext: {
        fontSize: FontSizes.downloadButtonText,
        color: 'black'
    },
});

export default AttachmentDownloadModal;
